package org.ahuanlien.crm.web.filter;

import com.alibaba.fastjson.JSON;
import org.ahuanlien.crm.util.JSONResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

public class MyFormAuthenticationFilter extends FormAuthenticationFilter {

	protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
		response.setContentType("application/json;charset=UTF-8");
		String json = JSON.toJSONString(new JSONResult());
		response.getWriter().print(json);
		return false;
	}

	protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
		response.setContentType("application/json;charset=UTF-8");
		e.printStackTrace();
		String errorMsg = "登录异常!请重试";
		if (e instanceof UnknownAccountException) {
			errorMsg = "帐号错误";
		} else if (e instanceof IncorrectCredentialsException) {
			errorMsg = "密码错误";
		}
		String json = JSON.toJSONString(JSONResult.mark(errorMsg));
		try {
			response.getWriter().print(json);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		return false;
	}

	//需求:重复登录,后登录的覆盖先登录的
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
		if (isLoginRequest(request, response)) {
			Subject subject = SecurityUtils.getSubject();
			if (subject.isAuthenticated()) {
				subject.logout();
			}
		}
		return super.isAccessAllowed(request, response, mappedValue);
	}
}
